package com.android.studyspot;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableOperationCallback;
import com.microsoft.windowsazure.mobileservices.TableQueryCallback;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;

public class UserProfileActivity extends SherlockActivity implements ConnectionCallbacks, OnConnectionFailedListener{
	private Menu userProfileMenu;
	private EditText firstName, lastName, email, school;
	private MobileServiceClient mClient;
	private MobileServiceTable<vw_users_schools> mUsersSchoolVw;
	private MobileServiceTable<vw_users_uc_courses> mUsersCoursesVw;
	private MobileServiceTable<users> mUsersTable;
	private Bundle hashmap;
	private ListView coursesListView;
	private ArrayList<String> courseList;
	private CustomAdapter courseAdapter;
	private Button editCoursesButton;
	private Typeface typeFace;
	
    private PlusClient mPlusClient;
	
	private boolean save = false;
	
	private static final  int CAL_POLY_ID = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//getSupportActionBar().setHomeButtonEnabled(true);
		
		typeFace = Typeface.createFromAsset(getAssets(),"fonts/futuraCondensed.ttf");
		
		hashmap = this.getIntent().getExtras();
		
		courseList = new ArrayList<String>();
		
		System.gc();
		initLayout();
		
		// Connect to Study Spot Azure Mobile Service
		try {
			mClient = new MobileServiceClient(
			    "https://studyspot.azure-mobile.net/",
				"UeeXTmfsscRIhhVuCyRqDRwfThBDPa90",
				this
			);
					
			this.mUsersSchoolVw = mClient.getTable(vw_users_schools.class);
			this.mUsersCoursesVw = mClient.getTable(vw_users_uc_courses.class);
			this.mUsersTable = mClient.getTable(users.class);
			
			populateProfile();
					
		}
		catch (MalformedURLException e) {
			Log.d("Azure", e.getMessage());
			e.printStackTrace();
		}
		
		mPlusClient = new PlusClient.Builder(this, this, this)
        .setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
        .build();
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.user_profile_menu, menu);
        this.userProfileMenu = menu;
        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.user_profile_edit:
				this.invalidateOptionsMenu();
				firstName.setEnabled(true);
				lastName.setEnabled(true);
			
				return true;
			case R.id.user_profile_save:
				this.invalidateOptionsMenu();
				updateUserInfo();
				return true;
				
			case R.id.user_profile_ss:
				Intent studySpotActivityStart = new Intent(UserProfileActivity.this, StudySpotsActivity.class);
				studySpotActivityStart.putExtra("userId", hashmap.getInt("userId"));
				
				int i = 0;
				
				for(String s: this.courseList){
					studySpotActivityStart.putExtra("course-" + i, s);
					
					i++;
				}	
				
				this.startActivity(studySpotActivityStart);			
				
				return true;
				
			default:
				return true;
		}
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (save) {
			menu.findItem(R.id.user_profile_save).setVisible(true);
			menu.findItem(R.id.user_profile_edit).setVisible(false);
			save = false;
		}
		else {
			menu.findItem(R.id.user_profile_save).setVisible(false);
			menu.findItem(R.id.user_profile_edit).setVisible(true);
			save = true;
		}
		
		return true;
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
        	if (mPlusClient.isConnected()) {
                mPlusClient.clearDefaultAccount();
                mPlusClient.disconnect();
                //mPlusClient.connect();
            }
        	
        	Intent intent = new Intent(this, LoginActivity.class);
        	startActivity(intent);
        	
            return true;
        }
        return false;
    }
	
	
	
	private void initLayout() {
		setContentView(R.layout.layout_user_profile);
		
		this.editCoursesButton = (Button)this.findViewById(R.id.edit_courses_button);
		
		this.editCoursesButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent addCoursesStart = new Intent(UserProfileActivity.this, AddCoursesActivity.class);
				addCoursesStart.putExtra("userId", hashmap.getInt("userId"));
				startActivity(addCoursesStart);
			}
			
		});
		
		this.firstName = (EditText)this.findViewById(R.id.first_name_field);
		this.lastName = (EditText)this.findViewById(R.id.last_name_field);
		this.email = (EditText)this.findViewById(R.id.email_field);
		this.school = (EditText)this.findViewById(R.id.school_field);
		
		coursesListView = (ListView)this.findViewById(R.id.profile_course_list_view);
		courseAdapter = new CustomAdapter(this, R.layout.list_item, courseList, typeFace);
		coursesListView.setAdapter(courseAdapter);
		
		setFont();
		
	}
	
	private void setFont() {
		TextView label;
		
		label = (TextView)this.findViewById(R.id.first_name_label);
		label.setTypeface(typeFace);
		
		label = (TextView)this.findViewById(R.id.last_name_label);
		label.setTypeface(typeFace);
		
		label = (TextView)this.findViewById(R.id.email_label);
		label.setTypeface(typeFace);
		
		label = (TextView)this.findViewById(R.id.school_label);
		label.setTypeface(typeFace);
		
		label = (TextView)this.findViewById(R.id.my_courses_title);
		label.setTypeface(typeFace);
		
		this.editCoursesButton.setTypeface(typeFace);
		
	}
	
	private void populateProfile() {
		
		this.mUsersSchoolVw.where().field("usr_id").eq(hashmap.getInt("userId"))
		.execute(new TableQueryCallback<vw_users_schools>() {

			@Override
			public void onCompleted(List<vw_users_schools> result, int count, Exception exception,
					ServiceFilterResponse response) {
				if (exception == null) {
					for (vw_users_schools item : result) {
						firstName.setText(item.firstname);
						firstName.setEnabled(false);
						lastName.setText(item.lastname);
						lastName.setEnabled(false);
						email.setText(item.email);
						email.setEnabled(false);
						school.setText(item.schoolname);
						school.setEnabled(false);
					}
					
					mUsersCoursesVw.where().field("usr_id").eq(hashmap.getInt("userId"))
					.execute(new TableQueryCallback<vw_users_uc_courses>() {

						@Override
						public void onCompleted(List<vw_users_uc_courses> result, int count,
								Exception exception, ServiceFilterResponse response) {
							if (exception == null) {
								SharedPreferences.Editor prefEditor = getSharedPreferences("userCourses", MODE_PRIVATE).edit();
								HashSet<String> courses = new HashSet<String>();
								
								for (vw_users_uc_courses item : result) {
									courseList.add(item.course);
									//append each class string
									courses.add(item.course);
								}
								courseAdapter.notifyDataSetChanged();
								
								//write it back
								prefEditor.putStringSet("courses", courses);
								prefEditor.commit();
							}
							else {
								Log.e("StudySpotFoo", exception.getMessage());
							}
							
						}
						
					});
				}
				else {
					Log.e("StudySpot", exception.getMessage());
				}
				
			}
			
		});
		
	}
	
	private void updateUserInfo() {
		firstName.setEnabled(false);
		lastName.setEnabled(false);
		email.setEnabled(false);
		
		users user = new users();
		user.id = this.hashmap.getInt("userId");
		user.firstname = firstName.getText().toString();
		user.lastname = lastName.getText().toString();
		user.email = email.getText().toString();
		user.u_school_id = UserProfileActivity.CAL_POLY_ID;
		this.mUsersTable.update(user, new TableOperationCallback<users>() {

			@Override
			public void onCompleted(users entity, Exception exception,
					ServiceFilterResponse response) {
				if (exception == null) {
					Log.d("StudySpot", "user info successfully updated");
				}
				else {
					Log.e("StudySpot", exception.getMessage());
				}
				
			}
			
		});
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Could not log out of Google+", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onConnected(Bundle arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Successfully logged out", Toast.LENGTH_SHORT).show();
	}	
}
